package com.andbase.demo.activity;

import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;

import com.andbase.demo.R;
import com.andbase.library.app.base.AbBaseActivity;
import com.andbase.library.utils.AbLogUtil;
import com.andbase.library.view.refresh.AbPullToRefreshView;

/**
 * WEB 通用页面 带刷新
 */
public class WebViewActivity extends AbBaseActivity {

    private WebView webView;
    private AbPullToRefreshView pullToRefreshView;
    private boolean loadingData = false;
    private String url = null;
    private String title = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //设置布局
        setContentView(R.layout.activity_web_view);

        url = this.getIntent().getStringExtra("url");
        title = getIntent().getStringExtra("title");

        setToolbarView(title,true);

        boolean refresh = getIntent().getBooleanExtra("refresh",false);

        AbLogUtil.e("WebView",url);

        pullToRefreshView = this.findViewById(R.id.pull_to_refresh);
        // 颜色
        pullToRefreshView.setColorSchemeColors(colorAccent);
        // 设置绘制的笑脸的宽度
        pullToRefreshView.setSmileStrokeWidth(8);
        // 笑脸动画转动的插值器
        pullToRefreshView.setSmileInterpolator(new LinearInterpolator());
        // 设置笑脸旋转动画的时长
        pullToRefreshView.setSmileAnimationDuration(2000);
        pullToRefreshView.setOnRefreshListener(new AbPullToRefreshView.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if(loadingData){
                    pullToRefreshView.setRefreshing(false);
                }else{
                    webView.clearCache(true);
                    webView.loadUrl(url);
                }

            }
        });

        if(!refresh){
            pullToRefreshView.setEnabled(false);
        }


        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                initWebView();
            }
        },100);

    }

    public void initWebView() {

        webView = new WebView(this);

        pullToRefreshView.addView(webView, new FrameLayout.LayoutParams(
                FrameLayout.LayoutParams.MATCH_PARENT,
                FrameLayout.LayoutParams.MATCH_PARENT));

        // 设置子视图是否允许滚动到顶部
        pullToRefreshView.setOnChildScrollUpCallback(new AbPullToRefreshView.OnChildScrollUpCallback() {
            @Override
            public boolean canChildScrollUp(AbPullToRefreshView parent, @Nullable View child) {
                return webView.getScrollY() > 0;
            }
        });

        initWebViewSettings(webView);

        webView.setWebViewClient(new WebViewClient() {

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                super.onReceivedSslError(view, handler, error);
            }

            /**
             * 防止加载网页时调起系统浏览器
             */
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                pullToRefreshView.setRefreshing(false);
                loadingData = false;
            }

        });

        webView.setWebChromeClient(new WebChromeClient() {

            @Override
            public void onReceivedTitle(WebView webView, String title) {
                super.onReceivedTitle(webView, title);
            }

            @Override
            public boolean onJsConfirm(WebView arg0, String arg1, String arg2,
                                       JsResult arg3) {
                return super.onJsConfirm(arg0, arg1, arg2, arg3);
            }


            @Override
            public boolean onJsAlert(WebView arg0, String arg1, String arg2,
                                     JsResult arg3) {
                return super.onJsAlert(null, arg1, arg2, arg3);
            }

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
            }
        });

        pullToRefreshView.setRefreshing(true);
        webView.loadUrl(url);
        loadingData = true;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //getMenuInflater().inflate(R.menu.menu_about, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == android.R.id.home) {
            back();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * 拦截返回键
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // 是否触发按键为back键
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            back();
            return true;
            // 如果不是back键正常响应
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    public void initWebViewSettings(WebView webView){
        try{
            WebSettings webSettings = webView.getSettings();
            webSettings.setJavaScriptEnabled(true);
            webSettings.setAllowFileAccess(true);
            webSettings.setDomStorageEnabled(true);
            webSettings.setSupportZoom(true);
            webSettings.setDefaultZoom(WebSettings.ZoomDensity.MEDIUM);
            webSettings.setBuiltInZoomControls(false);
            webSettings.setDefaultFontSize(20);
            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
                webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
            }
            //奇葩的背景透明色设置方法
            webView.setBackgroundColor(0);
            webView.setAlpha(0.99f);
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    private void back(){
        if(webView.canGoBack()){
            webView.goBack();
        }else{
            webView.destroy();
            finish();
        }
    }
}
